import httplib2
import re
from util import MonthToNumber

NASA_SITE_URL = "http://antwrp.gsfc.nasa.gov/apod/archivepix.html"
NASA_PHOTO_URL = "http://antwrp.gsfc.nasa.gov/apod/%s"

class WebInterface():

    def __init__(self):
        pass

    def GetHTML(self,url):
        """ 
            Get a html from any page
            and puts in a cache (./cache)
        """
        if not url:
            return ""

        h = httplib2.Http(".cache")
        r,c = h.request(url,"GET")
        return c

    def GetMainPage(self):
        """ Get the main page from NASA pics site """
        return self.GetHTML(NASA_SITE_URL)

    def GetPhotoPage(self,url):
        """ Get the photo page with details """
        if not url:
            return ""
        return self.GetHTML(NASA_PHOTO_URL % (url))

class PageParser():

    def GetPhotoList(self,content):
        """ 
            Get the list of urls names, and dates,
            processing only a list of \n
        
        """
        photo_list = []

        d_r = "(\d{4}\s\w*\s\d{2}|\w*\s\d{2}\s\d{4})"
        n_r = "<a href=\"(.*)\">(.*)</a>"

        regex = re.compile("^%s:.*%s.*$" % (d_r,n_r),re.I)
        regex_date_test = re.compile("^\d{4}.*$")

        for i in content:
            res = regex.match(i)
            if res:
                if regex_date_test.match(i):
                    date = res.group(1).split(" ")
                    photo_list.append({
                        'date':  "%s-%s-%s" % (date[0],MonthToNumber(date[1]),date[2]),
                        'title': res.group(3),
                        'link':  res.group(2)
                    })
                else:
                    date = res.group(1).split(" ")
                    photo_list.append({
                        'date':  "%s-%s-%s" % (date[2],MonthToNumber(date[0]),date[1]),
                        'title':res.group(3),
                        'link':res.group(2)
                    })

        return photo_list

    def GetPhotoPage(self,content):
        """
            Get the photo em data
        """

        return ""

if __name__ == "__main__":
    from optparse import OptionParser
    from os.path import isfile

    parser = OptionParser()
    parser.add_option("--web", "-w", action="store_true", help="Get web site main page")
    parser.add_option("--parse", "-p", action="store_true", help="Get web site main page with values parsed")
    parser.add_option("--file", "-f", type="string", help="Get file main page with values parsed")

    options, args = parser.parse_args()

    if options.web:
        wInterface = WebInterface()
        print wInterface.GetMainPage()
    
    if options.parse:
        wInterface = WebInterface()
        pInterface = PageParser()
        content = pInterface.GetMainPage().split("\n")
        for i in p.GetPhotoList(content): 
            print "%s" % i 
    
    if options.file:
        try:
            f = open(options.file,"r")
        except IOError:
            print "File not found"
            exit(-1)
        
        content = f.readlines()
        pInterface = PageParser()
        photo_list = pInterface.GetPhotoList(content)

        if len(photo_list) < 1:
            print "Bad parse, invalid file"
            exit(-1)

        for i in pInterface.GetPhotoList(content):
            print "%s" % i
